#include "msp.h"
#include "stdlib.h"

#define ACLK CS_CLKEN_ACLK_EN
#define MCLK CS_CLKEN_MCLK_EN
#define SMCLK CS_CLKEN_SMCLK_EN
#define HSMCLK CS_CLKEN_HSMCLK_EN
#define BCLK CS_STAT_BCLK_READY

#define CS_LFXTCLK 0x01

#define LFXT CS_CTL1_SELM_0
#define HFXT CS_CTL1_SELM_5
#define VLO CS_CTL1_SELM_1
#define REFO CS_CTL1_SELM_2
#define DCO CS_CTL1_SELM_3
#define MODOSC CS_CTL1_SELM_4

#define ACLK_DIV_BITPOS 0x04
#define MCLK_DIV_BITPOS 0x0C
#define SMCLK_DIV_BITPOS 0x00
#define HSMCLK_DIV_BITPOS 0x08

#define ACLK_SRC_BITPOS 0x08
#define MCLK_SRC_BITPOS 0x00
#define SMCLK_SRC_BITPOS 0x04
#define HSMCLK_SRC_BITPOS 0x04

#define CLOCK_DIVIDER_1 CS_CTL1_DIVS_0
#define CLOCK_DIVIDER_2 CS_CTL1_DIVS_1
#define CLOCK_DIVIDER_4 CS_CTL1_DIVS_2
#define CLOCK_DIVIDER_8 CS_CTL1_DIVS_3
#define CLOCK_DIVIDER_16 CS_CTL1_DIVS_4
#define CLOCK_DIVIDER_32 CS_CTL1_DIVS_5
#define CLOCK_DIVIDER_64 CS_CTL1_DIVS_6
#define CLOCK_DIVIDER_128 CS_CTL1_DIVS_7

#define CTL1_SELA_MASK ((uint32_t)0x00000700)  /*!< SELA Bit Mask */
#define CTL1_DIVA_MASK ((uint32_t)0x07000000)  /*!< DIVA Bit Mask */
#define CTL1_DIVS_MASK ((uint32_t)0x70000000)  /*!< DIVS Bit Mask */
#define CTL1_SELS_MASK ((uint32_t)0x00000070)  /*!< SELS Bit Mask */
#define CTL1_DIVHS_MASK ((uint32_t)0x00700000) /*!< DIVHS Bit Mask */
#define CLOCK_KEY 0x695A

#define DCO_FREQUENCY_1_5 CS_CTL0_DCORSEL_0
#define DCO_FREQUENCY_3 CS_CTL0_DCORSEL_1
#define DCO_FREQUENCY_6 CS_CTL0_DCORSEL_2
#define DCO_FREQUENCY_12 CS_CTL0_DCORSEL_3
#define DCO_FREQUENCY_24 CS_CTL0_DCORSEL_4
#define DCO_FREQUENCY_48 CS_CTL0_DCORSEL_5

#define CTL0_DCORSEL_MASK ((uint32_t)0x00070000) /*!< DCORSEL Bit Mask */

typedef void (*FUN)(void);
/**
 * @brief 设置时钟
 *
 * @param clock_signal 要修改的时钟信号
 * @param clock_source 使用的时钟源
 * @param divider 分频系数
 * @return uint8_t
 */
uint8_t Set_System_clock(uint32_t clock_signal, uint32_t clock_source,
                         uint32_t divider);
/**
 * @brief 修改DCO频率
 *
 * @param freq 频率
 * @return uint8_t
 */
uint8_t Set_DCO_Freq(uint32_t freq);